<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Fetch SSE Demo</title>
</head>
<body>
  <h1>Fetch API 实时消息推送</h1>
  <button onclick="connectFetch()">建立 Fetch 连接</button>
  <button onclick="closeFetch()">断开 Fetch 连接</button>
  <div id="messages"></div>

  <script>
    let controller;

    function connectFetch() {
      controller = new AbortController();
      const signal = controller.signal;

      fetch('http://localhost:3001/fetch-sse', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ content: '你好，服务器！' }),
        signal: signal
      })
      .then(response => {
        if (!response.body) {
          throw new Error('ReadableStream 不受支持');
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        const messages = document.getElementById('messages');

        function read() {
          return reader.read().then(({ done, value }) => {
            if (done) {
              console.log('Fetch 连接已关闭');
              return;
            }
            const chunk = decoder.decode(value, { stream: true });
            const data = JSON.parse(chunk);
            messages.innerHTML += `<p>${data.id} - ${data.time} - 参数：${JSON.stringify(data.body)}</p>`;
            return read();
          });
        }

        return read();
      })
      .catch(error => {
        if (error.name === 'AbortError') {
          console.log('Fetch 连接已中止');
        } else {
          console.error('Fetch 连接错误:', error);
        }
      });
    }

    function closeFetch() {
      if (controller) {
        controller.abort();
        controller = undefined;
        console.log('Fetch 连接已关闭2');
      }
    }
  </script>
</body>
</html>
